package com.li.blog.handler;

import com.alibaba.fastjson.JSON;
import com.li.blog.dao.pojo.SysUser;
import com.li.blog.service.LoginService;
import com.li.blog.utils.UserThreadLocal;
import com.li.blog.vo.ErrorCode;
import com.li.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

  @Autowired
  private LoginService loginService;
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    /**
     *
     * 1 是不是访问方法 不是直接放行 是就继续（拦截器主要拦截的是方法不是是静态文件）
     * 2 请求头中getHeader("Authorization"); 是否为空（为空就是没有登录过）这个是在查询用户信息的时候携带过来的
     * 3 在token不为空的情况检查token
     */
    if (!(handler instanceof HandlerMethod)){
      return true;
    }
    String token = request.getHeader("Authorization");

    log.info("=================request start===========================");
    String requestURI = request.getRequestURI();
    log.info("request uri:{}",requestURI);
    log.info("request method:{}",request.getMethod());
    log.info("token:{}", token);
    log.info("=================request end===========================");

    if (token==null){
      //设置result 进行返回
      //设置编码形式
      Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
      response.setContentType("application/json;charset=utf-8");
      response.getWriter().print(JSON.toJSONString(result));
      return false;
    }
    SysUser sysUser = loginService.checkToken(token);

    if (sysUser==null){
      Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
      response.setContentType("application/json;charset=utf-8");
      response.getWriter().print(JSON.toJSONString(result));
      return false;
    }
    UserThreadLocal.put(sysUser);
    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    UserThreadLocal.remove();
  }
}
